<template>
    <view class="page-list pd-v-24">
        <view class="page-list__header position-r pd-h-8">
            <view class="position-r">
              <u-search v-model="value" @change="input" :clearabled="false" :showAction="false" searchIconColor="#140701" placeholder="请输入充电站名称" height="34" bgColor="#ffffff" borderColor="#35BE65"  :animation="true"></u-search>
              <view class="search-btn font28 lh-40 color-white pd-h-8 pd-v-24 border30 position-a zIndex50" @click="search">
                  搜索
              </view>
            </view>
            
        </view>


        <view class="page-list__body">
            <view class="mr-t-30">
                <u-image src="@/static/5.gif" width="100%" mode="widthFix" @click="phone"></u-image>
            </view>

            <view class="flex mr-t-32">
                <view class="tag font26 lh-36 pd-v-24 pd-h-12 border30">
                    距离最近
                </view>
            </view>

            <view class="mr-t-20">
                <view class="border8 bg-white flex pd-v-24 pd-h-32 flex-center mr-b-12" v-for="(item,index) in list" :key="'item'+index" @click="goDetail(item)">
                    <view class="flex-1 mr-r-32">
                        <view class="font32 lh-44 bold color-default">
                            {{item.name}}
                        </view>
                        <view class="flex flex-center mr-t-20">
                            <view class="flex flex-center font24 lh-24 color-note">
                                <u-icon name="map-fill" color="#35BE65" size="16"></u-icon>
                                {{getDistance(item.location)}}
                            </view>
                            <view class="flex-1 mr-l-12 font24 lh-24 color-info line1" style="width:0">
                                {{item.spliceAddress}}
                            </view>
                                
                        </view>
                    </view>

                    <u-button type="primary" shape="circle" color="#35BE65" :customStyle="{width:'170rpx',height:'60rpx',padding:'14rpx 12rpx',fontSize:'24rpx'}" >
                      
                      <image src="@/static/battery.png" style="width:26rpx;" mode="widthFix" class="mr-r-6"></image>
                      {{item.socketFreeCount}}/{{item.socketTotalCount}}
                    </u-button>
                        
                </view>
                    
            </view>
              
              
        </view>
          
          
        <tab></tab>
    </view>
</template>

<script setup>
import { useStore } from '@/store/index.js';
import { ref, reactive, onMounted, nextTick } from 'vue';
import { onLoad, onShow,onReachBottom } from '@dcloudio/uni-app';
import { getStoreList } from '@/api/index/index.js'

import tab from '@/components/tab.vue'
// const QQMapWX = require('../../static/qqmap-wx-jssdk.js');
const amapFile  = require('../../static/amap-wx.130.js');

const store = useStore();
const list = ref([]);
const timer = ref(null);
const params = ref({
    pageNum: 1,
    pageSize: 10
})
const total = ref(0);
const currentLocation = ref('')
const value = ref('')

onShow(() => {
    
})

onLoad(() => {
    uni.getLocation({
        success: (res) => {
            console.log(res);
            currentLocation.value = res.longitude+','+res.latitude;
            
            // var myAmapFun = new amapFile.AMapWX({ key: '6fedb410f239b45906834cd2ac88a3f9' });

            // myAmapFun.getRegeo({
            //     success: function (data) {
            //         //成功回调
            //         console.log(data)
            //         currentLocation.value = {
            //             currentLocation:data[0].longitude+','+data[0].latitude,
            //             province:data[0].regeocodeData.addressComponent.province,
            //             city:data[0].regeocodeData.addressComponent.city,
            //             // district:data[0].regeocodeData.addressComponent.district
            //         };
                    
            //     },
            //     fail: function (info) {
            //         //失败回调
            //         console.log(info)
            //     }
            // })

            // const qqmapsdk = new QQMapWX({
            //     key: 'NZFBZ-U7T6R-EW5WI-WFRUF-I66JS-ZRFG4' // 必填
            // });
            storeList()
        },
        fail: (res) => {
            console.log('失败！！', res);
        }
    })

    

})



onReachBottom(() => {
    if(list.value.length >= total.value) return
    params.value.pageNum++
    storeList()
})

const input = (e) => {
    clearTimeout(timer.value);
    timer.value = setTimeout(() => {
        params.pageNum = 1
        list.value = []
        storeList()
    },1000)
}

const search = () => {
    clearTimeout(timer.value);
    params.pageNum = 1
    list.value = []
    storeList()
}

const storeList = () => {

    getStoreList({
        currentLocation:currentLocation.value,
        name:value.value,
        ...params.value
    }).then(res => {
        if(res.code == 200) {
            list.value = [...list.value,...res.rows]
            total.value = res.total
        }
    })
}

const goDetail = (item) => {
    if(!store?.user?.token) {
        uni.navigateTo({
            url: '/sub_user/pages/login/login'
        })
        return
    }
    uni.navigateTo({
        url: '/sub_user/pages/detail/detail?id='+item.id
    })
}

const getDistance = (location) => {
    if(!location) {
        return ''
    }
    let point1 = {
        latitude: currentLocation.value.split(',')[1],
        longitude: currentLocation.value.split(',')[0]
    }

    let point2 = {
        latitude: location.split(',')[1],
        longitude: location.split(',')[0]
    }
    let R = 6371000; // 地球平均半径，单位：米
    let lat1 = point1.latitude * Math.PI / 180;
    let lat2 = point2.latitude * Math.PI / 180;
    let lon1 = point1.longitude * Math.PI / 180;
    let lon2 = point2.longitude * Math.PI / 180;
    let a = Math.sin((lat2 - lat1) / 2) * Math.sin((lat2 - lat1) / 2) +
            Math.cos(lat1) * Math.cos(lat2) * Math.sin((lon2 - lon1) / 2) * Math.sin((lon2 - lon1) / 2);
    let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    let d = R * c; // 初始计算得到的距离，单位：米
 
    if (d >= 1000) {
        // 如果距离大于等于1000米（即1千米），则换算为千米并保留两位小数
        return (d / 1000).toFixed(2) + "km";
    } else {
        return d.toFixed(2) + "m";
    }
}

const phone = () => {
// #ifndef MP-WEIXIN
    uni.makePhoneCall({
        phoneNumber: store?.common?.platformInfo?.platformCustomerServicePhone
    });
// #endif

// #ifdef MP-WEIXIN
    wx.openOfficialAccountArticle({
        url:'https://mp.weixin.qq.com/s/nafApeayNAyZccnejlbKmg'
    })
// #endif
}
</script>

<style scoped lang="scss">
.page-list {
    background:#F7F7F7;
    min-height:100vh;
    padding-bottom:360rpx;

    .page-list__header {
        padding-top:176rpx;

        .search-btn {
            background: linear-gradient( 180deg, #7DE55B 0%, #39AAD1 100%);
            right:10rpx;
            top:50%;
            transform: translate3d(0, -50%, 0);
        }
       
    }

    .page-list__body {
        .tag{
            background: #EBEBEB;
            color:#15161F;
        }
    }
}
</style>
